﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using P2P_Backup.connections;

namespace P2P_Backup
{
    
    public class Backup
    {
        private archive.Archive archive;
        private List<RemotePeer> peers;
        private Thread backupThread;
        private int currentPeer;

        public Backup(archive.Archive ar, List<RemotePeer> peerList)
        {
            this.archive = ar;
            this.peers = peerList;
            backupThread = new Thread(new ThreadStart(this.doBackup));
            backupThread.IsBackground = true;
            backupThread.Start();
            ThreadPool.SetMaxThreads(10, 10);
        }

        private void doBackup()
        {
            //Check if available space is enough
                //Each peer has to share available disc space...
            if (peers.Count > 0)
                backupFolder(archive);
            else
                Console.WriteLine("No peers to preform backup");
        }
        private void backupFolder(archive.Folder folder)
        {
            foreach (archive.Folder f in folder.Folders)
            {
                backupFolder(f);
            }
            foreach(archive.File file in folder.Files.Where(f=> f.Status == P2P_Backup.archive.TransferStatus.New))
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(backupFile), file);
            }            
        }

        private void backupFile(Object o)
        {
            archive.File file = o as archive.File;
            RemotePeer peer = getNextPeer();
            file.BackupPeer = peer;

            LocalFileConnection fileConn = new LocalFileConnection(file);
            peer.sendCommand("BFT", String.Format("{0} {1} {2}", file.Id, file.Size, fileConn.EndPoint.Port));
            
            fileConn.Progress.Progressed += new EventHandler<FileConnectionArgs>(fileConn_Progess);
        }

        private void fileConn_Progess(object sender, FileConnectionArgs e)
        {
            if (e.File.Status == P2P_Backup.archive.TransferStatus.Complete)
            {
                archive.DataFile file = new archive.DataFile(e.File.BackupPeer);
                file.GenerateXml();

                LocalFileConnection fileConn = new LocalFileConnection(file);
                e.File.BackupPeer.sendCommand("BFT", String.Format("{0} {1} {2}", "data",file.Size, fileConn.EndPoint.Port));
            }
        }

        private RemotePeer getNextPeer()
        {
            RemotePeer result = peers[currentPeer % peers.Count];
            currentPeer++;
            return result;
        }
    }
}
